import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from config import result_bucket
from aws_model.athena_submit import submit
from sql_lambda.delete import delete_data
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def result_sspwl(event):
    date = event.get('p_date')
    if not date:
        date = datetime.datetime.today().strftime('%Y-%m-%d')
    table_name = sys._getframe().f_code.co_name
    delete_data(result_bucket,table_name, date)
    sql = f'''insert into fridge_biz_result.result_sspwl
                (
                    select
                        area,province,city,num,sum(num) over(partition by time) as month_num,all_num,time
                    from
                         (
                        select
                            if(t2.area is null,'',t2.area) as area,
                            concat(if(t2.province_name is null,'',t2.province_name),if(t2.province_suffix is null,'',t2.province_suffix)) as province,
                            if(t1.city is null,'',t1.city) as city,
                            sum(num) as num,
                            time
                        from
                            (
                                select
                                    substr(access_time,1,7) as time ,province_code,province,city, count(access_time) as num
                                from
                                    ods.device
                                where
                                    strpos(access_time,'-') > 0
                                and
                                    date(substr(access_time,1,10)) >= (date('{date}') - interval '1' month)
                                and
                                    date(substr(access_time,1,10)) < date('{date}')
                                and
                                    type = 'FRIDGE'
                                group by substr(access_time,1,7),province_code,province,city
                            ) t1
                        left join
                            dim.area_data t2
                        on
                            substr(t1.province_code,1,2) = t2.province_code
                        group by
                            time,
                            if(t2.area is null,'',t2.area),
                            if(t2.province_name is null,'',t2.province_name),
                            if(t2.province_suffix is null,'',t2.province_suffix),
                            if(t1.city is null,'',t1.city)
                        ) t3
                    left join
                        (
                            select count(1) as all_num from ods.device where type = 'FRIDGE'
                        )t4
                    on
                        true
                )'''

    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        result_sspwl(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)

